#import urllib2
#response = urllib2.urlopen("http://202km.com")
#page_source = response.read()
#print page_source

from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app
import re

MY_URL = "http://www.sit.kmutt.ac.th/sitnews/x_page7.php"
RSS_URL = "http://www.sit.kmutt.ac.th/sitnews/rss7news.php"
#MY_URL = "http://www.202km.com"
#MY_REG = re.compile(ur'<h2>.*?<span\s*class="en">(.*?)</span>.*?<span\s*class="th">(.*?)</span>')
MY_REG2 = re.compile(ur'.<font color="#009900">(.*?)</font>')
MY_REG3 = re.compile(ur'<td .*?<span class="normalforn"><font color="#000000"><a href="(.*?)" target="_blank">(.*?)</a>')
MY_REG4 = re.compile(ur'<td .*?<span class="normalforn"><font color="#000000"><a (.*?)>(.*?)</a>.*<font color="#999999">\[.([0-9]{2}/[0-9]{2}/[0-9]{4})')
MY_REG_FAIL = re.compile(ur'<item>.*?[[:space:]].*?<title>(.*?)</title>.*?[[:space:]].*?<link>(.*?)</link>.*?[[:space:]].*?<description>.*[[:space:]].*?<pubdate>([0-9]{4}-[0-9]{2}-[0-9]{2})</pubdate>.*[[:space:]].*</item>')
MY_REG = re.compile(ur'<title>(.*?)</title>\s*<link>(.*?)</link>\s*<description>.*\s*<pubdate>([0-9]{4}-[0-9]{2}-[0-9]{2})')
#prog = re.compile(pattern)
#result = prog.match(string)

def getPageHtml():
    rpc = urlfetch.create_rpc(deadline=10)
    urlfetch.make_fetch_call(rpc, RSS_URL)
    try:
        result = rpc.get_result()
        if result.status_code == 200:
            return result.content
    except urlfetch.DownloadError:
        return 'error'

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'#'text/plain'
        self.response.out.write('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />')

        content = getPageHtml()
        s = ''.join(content)
        s = s.decode('cp874')#.encode('utf8')
        #s = s.replace('\n','')
        #s = s.replace('\t','')
        #s = s.strip(' \t\n\r')
        result = MY_REG.findall(s)

        i = 1
        for item in result:
            self.response.out.write(item[0])
            self.response.out.write(" (DATE:"+item[2]+")")
            self.response.out.write('<br/>')
            self.response.out.write(item[1])
            self.response.out.write('<hr/>')

application = webapp.WSGIApplication(
    [
        (ur'/', MainPage)
    ],
    debug=True)

def main():
    run_wsgi_app(application)
    
if __name__ == "__main__":
    main()
